﻿using System.Threading.Tasks;
using Abp.Extensions;
using Abp.Web.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Vecen.BangChuang.BangChuang.Areas;
using Vecen.BangChuang.BangChuang.Areas.DomainDtos;
using Vecen.BangChuang.BangChuang.Areas.Dtos;

namespace Vecen.BangChuang.Controllers {
    /// <summary>
    /// IP地址
    /// </summary>
    [Route("api/[controller]/[action]")]
    public class AddressController: BangChuangControllerBase {
        private readonly ICityAppService _cityAppService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cityAppService"></param>
        public AddressController(ICityAppService cityAppService) {
            _cityAppService = cityAppService;
        }


        /// <summary>
        /// 根据请求获取地址
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<AjaxResponse<FullCityOutDto>> GetCityByRequestAsync() {
            return new AjaxResponse<FullCityOutDto>(await _cityAppService.GetByIp(GetIP(Request)));
        }


        /// <summary>
        ///     透过代理获取真实IP
        /// </summary>
        /// <param name="request">HttpContext</param>
        /// <returns>返回获取的ip地址</returns>
        private static string GetIP(HttpRequest request) {
            if(request == null) {
                return string.Empty;
            }

            bool isExistsProxy = request.Headers.TryGetValue("X-Fowarded-For", out StringValues value);
            if(isExistsProxy && !value.ToString().IsNullOrWhiteSpace()) {
                return value.ToString();
            }
            bool isExistsRemoteAddr = request.Headers.TryGetValue("REMOTE_ADDR", out value);
            if(isExistsRemoteAddr && !value.ToString().IsNullOrWhiteSpace()) {
                return value.ToString();
            }
            return request.Host.Host;
        }

        /// <summary>
        /// 根据坐标获取地址
        /// </summary>
        /// <param name="coordinate">坐标</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<AjaxResponse<FullCityOutDto>> GetCityByCoordinateAsync([FromQuery]Coordinate coordinate) {

            var address = await _cityAppService.GetByCoordinate(coordinate: coordinate);
            return new AjaxResponse<FullCityOutDto>(address);
        }
    }
}